from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
from starlette.templating import Jinja2Templates
import uvicorn

# 创建app对象
app = FastAPI()
# 设置密钥
SECRET_KEY = "081JlWpx1qlMLguHCDSNqKaZqrY7WnhwdKW7P43mgZs="
# 添加Session中间件
# 测试时设置10秒
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, max_age=10)
templates = Jinja2Templates(directory="templates")


# 添加Session路由函数
@app.get("/add")
async def session_set(request: Request):
    # 获取Session值
    counter = request.get("mysession", 0)
    # 累计1
    counter = int(counter) + 1
    # 设置Session值
    request.session["mysession"] = counter

    return templates.TemplateResponse(
        "index.html", {"request": request, "counter": counter}
    )


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)


# 清除Session路由函数
@app.get("/logout")
async def logout(request: Request):
    # 清除Session
    request.session.clear()
    response = templates.TemplateResponse("logout.html", {"request": request})
    # 删除Cookie
    response.set_cookie("mysession",value="",max_age=0)

    return response
